import pygame

class Building:
    def __init__(self, grid_x, grid_y, width, height, color):
        self.grid_x = grid_x
        self.grid_y = grid_y
        self.width = width
        self.height = height
        self.color = color
        self.is_valid = True  # 默认位置有效
        self.grid_valid = {}  # 存储每个格子的有效性
    
    def overlaps(self, other):
        # 检查两个建筑是否重叠
        return not (
            self.grid_x + self.width <= other.grid_x or
            other.grid_x + other.width <= self.grid_x or
            self.grid_y + self.height <= other.grid_y or
            other.grid_y + other.height <= self.grid_y
        )
    
    def draw(self, screen, terrain, is_preview=False):
        # 绘制建筑
        for x in range(self.width):
            for y in range(self.height):
                screen_x, screen_y = terrain.grid_to_screen(
                    self.grid_x + x,
                    self.grid_y + y
                )
                
                # 绘制建筑格子
                points = [
                    (screen_x, screen_y),
                    (screen_x + terrain.tile_size, screen_y - terrain.tile_height),
                    (screen_x + terrain.tile_size * 2, screen_y),
                    (screen_x + terrain.tile_size, screen_y + terrain.tile_height)
                ]
                
                if is_preview:
                    # 获取当前格子的有效性
                    grid_key = (x, y)
                    is_grid_valid = self.grid_valid.get(grid_key, self.is_valid)
                    
                    # 创建一个带alpha通道的surface
                    surf = pygame.Surface((terrain.tile_size * 2, terrain.tile_height * 2), pygame.SRCALPHA)
                    surf.fill((0, 0, 0, 0))  # 填充透明背景
                    
                    # 根据格子是否有效选择颜色
                    preview_color = (0, 255, 0, 128) if is_grid_valid else (255, 0, 0, 128)
                    border_color = (0, 255, 0) if is_grid_valid else (255, 0, 0)
                    
                    # 在surface上绘制填充的多边形
                    adjusted_points = [(p[0] - screen_x, p[1] - (screen_y - terrain.tile_height)) for p in points]
                    pygame.draw.polygon(surf, preview_color, adjusted_points)
                    
                    # 将surface绘制到屏幕上
                    screen.blit(surf, (screen_x, screen_y - terrain.tile_height))
                    
                    # 绘制边框
                    pygame.draw.polygon(screen, border_color, points, 2)
                else:
                    pygame.draw.polygon(screen, self.color, points)
                    pygame.draw.polygon(screen, (0, 0, 0), points, 1)